import { apiClient } from './index'
import { mockApi } from '@/utils/mockApi'
import type { 
  MonitoredTable, 
  TableStatistics, 
  TableSchema, 
  LayerOverview, 
  DashboardStats,
  ApiResponse,
  PaginationResponse,
  QueryParams 
} from '@/types'

export const monitorApi = {
  // 获取仪表板统计数据
  getDashboardStats: async (): Promise<ApiResponse<DashboardStats>> => {
    return mockApi.monitor.getDashboardStats()
  },

  // 获取数据层概览
  getLayersOverview: async (): Promise<ApiResponse<LayerOverview[]>> => {
    const stats = await mockApi.monitor.getDashboardStats()
    return {
      code: 200,
      message: 'success',
      data: stats.data.layers,
      timestamp: new Date().toISOString()
    }
  },

  // 获取指定层详情
  getLayerDetail: async (layer: string): Promise<ApiResponse<LayerOverview>> => {
    const stats = await mockApi.monitor.getDashboardStats()
    const layerData = stats.data.layers.find(l => l.layer === layer)
    return {
      code: 200,
      message: 'success',
      data: layerData!,
      timestamp: new Date().toISOString()
    }
  },

  // 获取监控表列表
  async getTables(params: { page?: number; size?: number; search?: string; layer?: string; is_monitored?: boolean | string }) {
    return mockApi.monitor.getTables(params)
  },

  // 用于趋势选择的表清单
  async getTrendTables(params?: { layer?: string; is_monitored?: boolean | string }): Promise<ApiResponse<Array<{ table_id: number; table_name: string; layer: string }>>> {
    const tables = await mockApi.monitor.getTables({})
    const items = (tables.data.items || []).map((t: any) => ({ table_id: t.id, table_name: t.table_name, layer: t.layer }))
    return {
      code: 200,
      message: 'success',
      data: items,
      timestamp: new Date().toISOString()
    }
  },

  // 新增：趋势指标（表数量/数据量）序列
  async getTrendMetrics(params: { metric: 'table_count' | 'data_size'; granularity: 'hour' | 'day' }): Promise<ApiResponse<Array<{ time: string; value: number }>>> {
    const now = new Date()
    const points: Array<{ time: string; value: number }> = []
    if (params.granularity === 'hour') {
      for (let i = 23; i >= 0; i--) {
        const d = new Date(now.getTime() - i * 3600 * 1000)
        const yyyy = d.getFullYear(); const mm = String(d.getMonth() + 1).padStart(2, '0'); const dd = String(d.getDate()).padStart(2, '0'); const hh = String(d.getHours()).padStart(2, '0')
        // 表数量较平稳，数据量波动更大
        const base = params.metric === 'table_count' ? 1000 : 500 * 1024 * 1024
        const jitter = params.metric === 'table_count' ? Math.floor(Math.random() * 10) : Math.floor(Math.random() * 50 * 1024 * 1024)
        points.push({ time: `${yyyy}-${mm}-${dd} ${hh}:00`, value: base + jitter })
      }
    } else {
      for (let i = 29; i >= 0; i--) {
        const d = new Date(now.getTime() - i * 24 * 3600 * 1000)
        const yyyy = d.getFullYear(); const mm = String(d.getMonth() + 1).padStart(2, '0'); const dd = String(d.getDate()).padStart(2, '0')
        const base = params.metric === 'table_count' ? 1000 : 500 * 1024 * 1024
        const drift = params.metric === 'table_count' ? i * 0.3 : i * 5 * 1024 * 1024
        const jitter = params.metric === 'table_count' ? Math.floor(Math.random() * 20) : Math.floor(Math.random() * 80 * 1024 * 1024)
        points.push({ time: `${yyyy}-${mm}-${dd}`, value: Math.max(0, Math.floor(base + drift + jitter)) })
      }
    }
    return {
      code: 200,
      message: 'success',
      data: points,
      timestamp: new Date().toISOString()
    }
  },

  // 获取表详情
  getTableDetail: async (tableId: number): Promise<ApiResponse<MonitoredTable>> => {
    const tables = await mockApi.monitor.getTables()
    const table = tables.data.items.find(t => t.id === tableId)
    return {
      code: 200,
      message: 'success',
      data: table!,
      timestamp: new Date().toISOString()
    }
  },

  // 获取表统计数据
  getTableStatistics: async (
    tableId: number, 
    startTime: string, 
    endTime: string
  ): Promise<ApiResponse<TableStatistics[]>> => {
    // 模拟统计数据
    const mockStats: TableStatistics[] = [
      {
        id: 1,
        table_id: tableId,
        record_time: '2024-01-15T10:00:00Z',
        row_count: 1000000,
        data_size: 204857600,
        increment_count: 15000,
        partition_count: 7,
        avg_row_size: 204.86,
        created_at: '2024-01-15T10:00:00Z'
      }
    ]
    
    return {
      code: 200,
      message: 'success',
      data: mockStats,
      timestamp: new Date().toISOString()
    }
  },

  // 获取表结构信息
  getTableSchema: async (tableId: number): Promise<ApiResponse<TableSchema[]>> => {
    // 模拟表结构数据
    const mockSchema: TableSchema[] = [
      {
        id: 1,
        table_id: tableId,
        column_name: 'uid',
        data_type: 'STRING',
        is_nullable: false,
        is_primary_key: false,
        is_partition_key: false,
        description: '用户唯一标识',
        ordinal_position: 1,
        created_at: '2024-01-01T00:00:00Z',
        updated_at: new Date().toISOString()
      },
      {
        id: 2,
        table_id: tableId,
        column_name: 'etl_date',
        data_type: 'DATETIME',
        is_nullable: false,
        is_primary_key: false,
        is_partition_key: true,
        description: '数据更新时间',
        ordinal_position: 2,
        created_at: '2024-01-01T00:00:00Z',
        updated_at: new Date().toISOString()
      }
    ]
    
    return {
      code: 200,
      message: 'success',
      data: mockSchema,
      timestamp: new Date().toISOString()
    }
  },

  // 获取异常数据
  getAnomalies: async (params?: QueryParams): Promise<ApiResponse<any[]>> => {
    return {
      code: 200,
      message: 'success',
      data: [],
      timestamp: new Date().toISOString()
    }
  },

  // 创建监控表
  createTable: async (data: Partial<MonitoredTable>): Promise<ApiResponse<MonitoredTable>> => {
    return {
      code: 200,
      message: 'success',
      data: data as MonitoredTable,
      timestamp: new Date().toISOString()
    }
  },

  // 更新监控表
  updateTable: async (tableId: number, data: Partial<MonitoredTable>): Promise<ApiResponse<MonitoredTable>> => {
    return {
      code: 200,
      message: 'success',
      data: data as MonitoredTable,
      timestamp: new Date().toISOString()
    }
  },

  // 删除监控表
  deleteTable: async (tableId: number): Promise<ApiResponse<void>> => {
    return {
      code: 200,
      message: 'success',
      data: undefined,
      timestamp: new Date().toISOString()
    }
  },

  // 启用/禁用监控
  async toggleTableMonitoring(id: number, is_monitored: boolean): Promise<ApiResponse<void>> {
    // mock 切换
    return {
      code: 200,
      message: 'success',
      data: undefined,
      timestamp: new Date().toISOString()
    }
  },
  async batchToggleMonitoring(ids: number[], is_monitored: boolean): Promise<ApiResponse<void>> {
    return {
      code: 200,
      message: 'success',
      data: undefined,
      timestamp: new Date().toISOString()
    }
  },

  // 统计：每日增量
  async getDailyIncrements(params: { layer?: string; start_date?: string; end_date?: string; is_monitored?: boolean | string }): Promise<ApiResponse<any[]>> {
    return {
      code: 200,
      message: 'success',
      data: [
        { table_id: 7, table_name: 'ods_event_log', layer: 'ODS', date: '2024-01-14', increment_count: 18234 },
        { table_id: 7, table_name: 'ods_event_log', layer: 'ODS', date: '2024-01-15', increment_count: 22340 },
        { table_id: 8, table_name: 'dwd_order_detail', layer: 'DWD', date: '2024-01-14', increment_count: 9234 },
        { table_id: 8, table_name: 'dwd_order_detail', layer: 'DWD', date: '2024-01-15', increment_count: 12834 },
        { table_id: 3, table_name: 'dwd_user_behavior_daily', layer: 'DWD', date: '2024-01-14', increment_count: 5234 },
        { table_id: 3, table_name: 'dwd_user_behavior_daily', layer: 'DWD', date: '2024-01-15', increment_count: 8634 }
      ],
      timestamp: new Date().toISOString()
    }
  },

  // 统计：无更新表（今日）
  async getNoUpdateToday(params: { layer?: string; threshold_hours?: number; is_monitored?: boolean | string }): Promise<ApiResponse<any[]>> {
    return {
      code: 200,
      message: 'success',
      data: [
        { table_id: 5, table_name: 'dim_product_category', layer: 'DIM', last_update_time: '2024-01-12 18:00:00' },
        { table_id: 4, table_name: 'dws_user_profile_summary', layer: 'DWS', last_update_time: '2024-01-14 02:00:00' }
      ],
      timestamp: new Date().toISOString()
    }
  },

  // 统计：当日新增
  async getTodayNew(params: { layer?: string; is_monitored?: boolean | string }): Promise<ApiResponse<any[]>> {
    return {
      code: 200,
      message: 'success',
      data: [
        { table_id: 7, table_name: 'ods_event_log', layer: 'ODS', new_partitions: 1, today_increment: 12000 },
        { table_id: 8, table_name: 'dwd_order_detail', layer: 'DWD', new_partitions: 0, today_increment: 9800 }
      ],
      timestamp: new Date().toISOString()
    }
  },

  // 统计：TOP 排行
  async getTopTables(params: { metric: 'increment' | 'size'; range: '1d' | '7d' | '30d'; layer?: string; is_monitored?: boolean | string; limit?: number }): Promise<ApiResponse<any[]>> {
    return {
      code: 200,
      message: 'success',
      data: [
        { table_id: 7, table_name: 'ods_event_log', layer: 'ODS', metric_value: 198765 },
        { table_id: 8, table_name: 'dwd_order_detail', layer: 'DWD', metric_value: 167890 },
        { table_id: 3, table_name: 'dwd_user_behavior_daily', layer: 'DWD', metric_value: 102345 }
      ],
      timestamp: new Date().toISOString()
    }
  },

  // 统计：通用增量接口（日/小时）
  async getIncrements(params: { table_id: number; granularity: 'hour' | 'day'; start_time?: string; end_time?: string }): Promise<ApiResponse<Array<{ time: string; increment: number }>>> {
    const now = new Date()
    const points: Array<{ time: string; increment: number }> = []
    if (params.granularity === 'hour') {
      // 生成过去24小时的模拟数据，整点
      for (let i = 23; i >= 0; i--) {
        const d = new Date(now.getTime() - i * 3600 * 1000)
        const hh = String(d.getHours()).padStart(2, '0')
        const yyyy = d.getFullYear()
        const mm = String(d.getMonth() + 1).padStart(2, '0')
        const dd = String(d.getDate()).padStart(2, '0')
        points.push({ time: `${yyyy}-${mm}-${dd} ${hh}:00`, increment: Math.floor(500 + Math.random() * 1500) })
      }
    } else {
      // 生成过去7天的模拟数据，按日
      for (let i = 6; i >= 0; i--) {
        const d = new Date(now.getTime() - i * 24 * 3600 * 1000)
        const yyyy = d.getFullYear()
        const mm = String(d.getMonth() + 1).padStart(2, '0')
        const dd = String(d.getDate()).padStart(2, '0')
        points.push({ time: `${yyyy}-${mm}-${dd}`, increment: Math.floor(5000 + Math.random() * 8000) })
      }
    }
    return {
      code: 200,
      message: 'success',
      data: points,
      timestamp: new Date().toISOString()
    }
  }
} 